package org.example.consumer;

import com.rabbitmq.client.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RabbitMqConsumer {

    @SneakyThrows
    public static void createRabbitMqConsumer() {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername("admin");
        factory.setPassword("10086");
        factory.setHost("miaomiaole");
        factory.setPort(7672);
        factory.setVirtualHost("/");
        // 建立到代理服务器连接
        Connection connection = factory.newConnection();
        // 创建信道
        final Channel channel = connection.createChannel();
        // 声明交换器
        channel.exchangeDeclare("directExchange", "direct", true);
        // 声明队列
        String queueName = channel.queueDeclare().getQueue();
        // 队列与交换器绑定
        channel.queueBind(queueName, "directExchange", "directRouteKey");

        // 消费消息 不断循环等待服务器推送消息
        while (true) {
            boolean autoAck = false;
            String consumerTag = "";
            channel.basicConsume(queueName, autoAck, consumerTag, new DefaultConsumer(channel) {
                @Override
                @SneakyThrows
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) {
                    String routingKey = envelope.getRoutingKey();
                    String contentType = properties.getContentType();
                    log.info("消费路由键：{}", routingKey);
                    log.info("消费的消息体内容：{}", contentType);
                    long deliveryTag = envelope.getDeliveryTag();
                    // 确认消息
                    channel.basicAck(deliveryTag, false);
                    log.info("Message:{}", new String(body));

                }
            });
        }
    }
}
